package com.hhc.service.impl;

import com.hhc.dto.FileDeleteDTO;
import com.hhc.dto.FileDownloadDTO;
import com.hhc.dto.FileUploadDTO;
import com.hhc.entity.FileResource;
import com.hhc.query.FileListQuery;
import com.hhc.repository.FileResourceRepository;
import com.hhc.service.FileResourceService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文件资源服务实现类
 *
 * @author pc
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class FileResourceServiceImpl implements FileResourceService {

    private final FileResourceRepository fileResourceRepository;

    @Override
    @Transactional
    public boolean uploadFile(FileUploadDTO dto) {
        log.info("开始上传文件，原始文件名：{}", dto.getOriginalName());

        // 判断文件是否已存在
        Optional<FileResource> existingFile = fileResourceRepository.findByOriginalName(dto.getOriginalName());
        if (existingFile.isPresent()) {
            log.warn("文件已存在，原始文件名为：{}", dto.getOriginalName());
            return false; // 表示文件已经存在
        }

        // 构建新的文件资源对象
        FileResource resource = new FileResource();
        resource.setOriginalName(dto.getOriginalName());
        resource.setStoragePath(dto.getStoragePath());
        resource.setFileSize(dto.getFileSize());
        resource.setMimeType(dto.getMimeType());
        resource.setUploadUserId(dto.getUploadUserId());
        resource.setCategory(dto.getCategory());
        resource.setDescription(dto.getDescription());
        resource.setCreateBy("admin"); // 可根据实际业务设置创建人
        resource.setCreateTime(LocalDateTime.now());
        resource.setUpdateBy("admin");
        resource.setUpdateTime(LocalDateTime.now());

        try {
            fileResourceRepository.save(resource);
            log.info("文件上传成功，ID为：{}", resource.getId());
            return true;
        } catch (Exception e) {
            log.error("文件上传失败，错误原因：{}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public FileResource downloadFile(FileDownloadDTO dto) {
        log.info("开始下载文件，ID为：{}", dto.getId());

        Optional<FileResource> optionalFile = fileResourceRepository.findById(dto.getId());
        if (!optionalFile.isPresent()) {
            log.warn("文件不存在，ID为：{}", dto.getId());
            return null;
        }

        log.info("文件下载成功，ID为：{}", dto.getId());
        return optionalFile.get();
    }

    @Override
    @Transactional
    public boolean deleteFile(FileDeleteDTO dto) {
        log.info("开始删除文件，ID为：{}", dto.getId());

        Optional<FileResource> optionalFile = fileResourceRepository.findById(dto.getId());
        if (!optionalFile.isPresent()) {
            log.warn("文件不存在，ID为：{}", dto.getId());
            return false;
        }

        try {
            fileResourceRepository.deleteById(dto.getId());
            log.info("文件删除成功，ID为：{}", dto.getId());
            return true;
        } catch (Exception e) {
            log.error("文件删除失败，ID为：{} 错误原因：{}", dto.getId(), e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public List<FileResource> getFileList(FileListQuery query, Pageable pageable) {
        log.info("获取文件列表");

        return fileResourceRepository.findByCategoryAndKeyword(
                query.getCategory(),
                query.getKeyword()
        );
    }
}